<?php

namespace App\Console\Commands\Mybank\Tools;

use App\Kuafu\Mybank\Model\MybankBillRecordModel;
use App\Kuafu\Mybank\Service\MybankService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class QueryBatchMoneyDiffCommand extends Command
{
    protected $signature = 'mybank:tools:query-batch-money-diff';

    protected $description = '批次状态查询';

    public function handle()
    {
        $source    = MybankBillRecordModel::SOURCE_CANTEEN;
        $startDate = strtotime(date('y-m-d')); // 今天

        $billRecordList = MybankBillRecordModel::getBillRecordList(
            0, MybankBillRecordModel::WITHDRAW_TRANS_TYPE,
            MybankBillRecordModel::DEFAULT_FLAG_MARK, 0,
            $source, $startDate, $startDate + 86399);

        $data        = [];
        $totalAmount = 0;

        foreach ($billRecordList as $billRecord) {
            $getMerchantInfo = MybankService::getMerchantIdByShopId($billRecord['shopId']);
            if (!$getMerchantInfo['merchantId']) { // 排除无商户id
                Log::channel('mybank')
                   ->notice('分账数据-排除无商户id记录', [
                       'shopId'       => $billRecord['shopId'],
                       'fsNotifyUids' => [
                           '3fgc8798',
                       ]
                   ]);
                continue;
            }
            $totalAmount += $billRecord['transAmount'];
            $data[]      = array_merge($billRecord, [
                'entryId'      => $getMerchantInfo['entryId'],
                'merchantId'   => $getMerchantInfo['merchantId'],
                'merchantName' => $getMerchantInfo['merchantName']
            ]);
        }

        switch ($source) {
            // 堂食
            case MybankBillRecordModel::SOURCE_CANTEEN:
                $filter = [];
                // 检查每个人的金额是否异常
                $fuyouBillRecordDates = MybankService::matchFuyouBillRecordByDate($data, true);

                foreach ($fuyouBillRecordDates as $key => $recordData) {
                    $filter[$key]['transactionAmount'] = array_sum(array_column($recordData,
                        'transactionAmount'));
                    $filter[$key]['transactionFee']    = array_sum(array_column($recordData,
                        'transactionFee'));
                    $filter[$key]['actualAmount']      = $filter[$key]['transactionAmount'] - $filter[$key]['transactionFee'];
                }

                foreach ($billRecordList as $key => $item) {

                    if ($item['transAmount'] != $filter[$item['shopId']]['actualAmount']) {
                        dump('数据不同');
                        dump($item);
                        dump($filter[$item['shopId']]);
                        dump('----');
//                        die;
                    }
                }
                break;

        }
    }
}
